package com.dxj.security.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dxj.domain.User;
import com.dxj.mapper.PermissionMapper;
import com.dxj.mapper.RoleMapper;
import com.dxj.mapper.UserMapper;
import com.dxj.security.domain.LoginUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.*;

/**
 * @author dxj
 * @Description 用户认证实现类 从数据库中查找用户，并实现并实现自定义的逻辑
 * @date 2024/7/28 15:16
 */
@Component
public class UserServiceAuthImpl implements UserDetailsService{
    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private PermissionMapper permissionMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        User user=getUserByUsername(username);
        //查询角色码信息
        Set<String> userRoles=roleMapper.getRoleById(user.getId());
        //查询权限码信息
        Set<String> permissionList=permissionMapper.getUserPermissionById(user.getId());
        return LoginUser.builder()
                .id(user.getId())
                .userName(user.getUserName())
                .passWord(user.getPassWord())
                .permissions(permissionList)
                .roles(userRoles)
                .build();
    }

    /**
     * 从数据库查询用户信息
     * @param username
     * @return User
     */
    public User getUserByUsername(String username) {
        Optional<User> optional = Optional.ofNullable(userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserName,username)));
        return optional.orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
    }
}
